package common

import (
	"beesoft.ink/application/media/app/g"
	model "beesoft.ink/application/media/app/model/category"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
)

var Tag tag

type tag struct{}

func (r *tag) List(ctx iris.Context, req *model.TagListReq) ([]model.Tag, error) {
	m := g.DB().NewSession()
	if req.Type != 0 {
		m = m.Where("type = ?", req.Type)
	}
	if req.Order != "" {
		if req.OrderDirection {
			m = m.Desc(req.Order)
		} else {
			m = m.Asc(req.Order)
		}
	}

	var items []model.Tag
	err := m.
		Limit(req.PageSize, req.PageSize*(req.Page-1)).
		Find(&items)
	if err != nil {
		panic(err)
	}

	for i, item := range items {
		err := json.Unmarshal([]byte(item.Title), &items[i].Titles)
		if err != nil {
			fmt.Printf("LanguageList JsonDecode error: %+v", err)
		}
	}

	return items, nil
}
